package com.user_service.service;

import com.user_service.bean.User;
import com.user_service.repository.UserRepository;
import com.user_service.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@RequiredArgsConstructor
public class UserService {
    private final UserRepository userRepository;
    private final JwtUtil jwtUtil;
    private final GlobalIndexService globalIndexService;
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    public User registerUser(String username, String password, String email){
        User user=new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password)); // 使用BCrypt加密密码
        user.setEmail(email);
        User savedUser = userRepository.save(user);
        // 添加到全局索引
        globalIndexService.addUserIndex(savedUser.getId(), email, username);
        return savedUser;
    }

    public Optional<User> findByUsername(String username){
        // 先通过全局索引查找
        Long userId = globalIndexService.getUserIdByUsername(username);
        if (userId != null) {
            return userRepository.findById(userId);
        }
        // 如果全局索引中没有，则直接查询数据库
        return userRepository.findByUsername(username);
    }
    
    public Optional<User> findByEmail(String email) {
        // 先通过全局索引查找
        Long userId = globalIndexService.getUserIdByEmail(email);
        if (userId != null) {
            return userRepository.findById(userId);
        }
        // 如果全局索引中没有，则直接查询数据库
        return userRepository.findByEmail(email);
    }

    public Boolean existsByUsername(String username){
        return globalIndexService.getUserIdByUsername(username) != null || userRepository.existsByUsername(username);
    }
    
    public Boolean existsByEmail(String email) {
        return globalIndexService.getUserIdByEmail(email) != null || userRepository.existsByEmail(email);
    }

    public Optional<User> findById(Long id){
        return userRepository.findById(id);
    }
    
    // 添加登录方法
    public Optional<User> login(String username, String password) {
        return findByUsername(username)
                .filter(user -> passwordEncoder.matches(password, user.getPassword())); // 使用BCrypt验证密码
    }
    
    // 生成用户token
    public String generateToken(User user) {
        return jwtUtil.generateToken(user.getId());
    }
    
    // 验证用户token
    public Boolean validateToken(String token, Long userId) {
        return jwtUtil.validateToken(token, userId);
    }
}